// 聊天服务相关的组合式函数
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ChatMessage } from '@/types/chat'
import * as _ from 'lodash'
import { marked } from 'marked'

export function useChatService() {
  const loading = ref(false)
  const loadingText = ref('思考中')
  const processing = ref(false)
  let intervalId: number | null = null
  let controller: AbortController | null = null

  const models: any = []

  // 开发环境配置：是否显示思考过程（仅用于调试）
  const showThinkingProcess = ref<boolean>(false) // 默认关闭，需要时可手动开启

  // 打字机效果配置
  const typewriterEnabled = ref<boolean>(true) // 是否启用打字机效果
  const typewriterSpeed = ref<number>(30) // 打字速度（毫秒）

  // 性能监控和缓存相关状态
  const renderingStats = ref({
    totalRenderTime: 0,
    renderCount: 0,
    averageRenderTime: 0,
    lastRenderTime: 0,
    cacheHits: 0,
    cacheMisses: 0,
  })

  // 内容缓存映射
  const contentCache = new Map<string, { html: string; timestamp: number }>()

  // 更新加载文本的方法
  function updateLoadingText() {
    if (!loading.value) return

    const dots = loadingText.value.split('.').length - 1
    loadingText.value = '思考中 ' + '.'.repeat((dots % 3) + 1)
  }

  // 开始加载动画
  function startLoadingAnimation() {
    loading.value = true
    intervalId = window.setInterval(updateLoadingText, 1000)
  }

  // 停止加载动画
  function stopLoadingAnimation() {
    loading.value = false
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
  }

  // 停止处理
  const stopProcessing = () => {
    if (controller) {
      controller.abort()
    }
    processing.value = false
    stopLoadingAnimation()
  }

  // 保存消息到服务器（已废弃，使用 historyStore.saveMessage 替代）
  const saveMessage = async (message: ChatMessage, sessionId: string) => {
    console.warn('saveMessage 已废弃，请使用 historyStore.saveMessage')
    return sessionId || 'new-session-id'
  }

  // 发送消息到AI模型
  const sendToAI = async (
    question: string,
    currentModel: string,
    chatMessages: ChatMessage[],
    sessionId: string,
    deepseekConfig?: any,
    saveMessageCallback?: (message: ChatMessage) => Promise<void>,
    extendData?: any,
  ) => {
    startLoadingAnimation()
    processing.value = true

    // 添加思考中的消息
    const thinkingMessage: ChatMessage = {
      content: '思考中',
      sender: 'chat',
      timestamp: Date.now(),
    }
    chatMessages.push(thinkingMessage)

    try {
      controller = new AbortController()
      const signal = controller.signal

      const url = `${import.meta.env.VITE_API_BASE_URL}/euc/api/chat/message/flux`
      const apiKey = 'app-LL0DDROGsXJn3XCaf1sQgxUM'
      const headers = {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        accept: 'text/event-stream',
      }
      const requestData = {
        inputs: {},
        message: question,
        response_mode: 'streaming',
        conversation_id: '',
        user: 'abc-123',
        files: [],
        model: currentModel,
        ...extendData,
      }

      const response = await fetch(url, {
        signal,
        method: 'POST',
        headers,
        body: JSON.stringify(requestData),
      })

      if (response.ok) {
        await processStreamResponse(response, currentModel, chatMessages)
        // 保存AI回复
        if (saveMessageCallback) {
          const lastMessage = chatMessages[chatMessages.length - 1]
          if (sessionId) {
            lastMessage.sessionId = sessionId
          }
          await saveMessageCallback(lastMessage)
        }
      } else {
        throw new Error(`请求失败: ${response.status}`)
      }
    } catch (error) {
      console.error('AI请求失败:', error)
      if (error instanceof Error) {
        ElMessage.error(error.message)
      }
      // 移除思考中的消息
      chatMessages.pop()
    } finally {
      stopLoadingAnimation()
      processing.value = false
    }
  }

  // 处理流式响应
  const processStreamResponse = async (
    response: Response,
    _currentModel: string,
    chatMessages: ChatMessage[],
  ) => {
    const reader = response.body?.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let combinedData = ''
    let firstDataReceived = false
    if (reader) {
      let isReading = true
      while (isReading) {
        const { value, done } = await reader.read()
        if (done) {
          isReading = false
          break
        }
        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (line) {
            let res = null
            let json: any = {}

            try {
              // 尝试解析 JSON，支持不同的前缀格式
              if (line.startsWith('data:data:')) {
                json = JSON.parse(line.substring(10))
              } else if (line.startsWith('data: ')) {
                json = JSON.parse(line.substring(6))
              } else if (line.startsWith('data:')) {
                json = JSON.parse(line.substring(5))
              } else {
                json = JSON.parse(line)
              }
            } catch (error) {
              // 解析失败，跳过这一行
              continue
            }

            // 兼容两种事件类型
            const eventType = json['event']

            // 处理 "message" 事件（原有格式）
            if (eventType === 'message') {
              res = _.get(json, 'answer')
            }
            // 处理 "text_chunk" 事件（新格式）
            else if (eventType === 'text_chunk') {
              res = _.get(json, 'data.text')
            }
            // 如果都不是，跳过
            else {
              continue
            }

            // 如果获取到了文本内容
            if (res) {
              combinedData += res
              if (!firstDataReceived) {
                stopLoadingAnimation()
                firstDataReceived = true
              }
            }
            let processedContent = ''
            const parts = combinedData.split(/(<think>|<\/think>)/)
            let isInThink = false
            for (let i = 0; i < parts.length; i++) {
              if (parts[i] === '<think>') {
                isInThink = true
                continue
              } else if (parts[i] === '</think>') {
                isInThink = false
                continue
              }

              if (isInThink) {
                const parsed = marked.parse(parts[i])
                processedContent += `<div style="color:#8b8b8b;">${parsed}</div>`
              } else {
                processedContent += marked.parse(parts[i])
              }
            }
            chatMessages[chatMessages.length - 1].content = processedContent
          }
        }
      }
    }
  }

  // 检查敏感词
  const checkSensitiveWords = async (content: string): Promise<boolean> => {
    try {
      // 这里需要实际的敏感词检查API
      // const result = await hasContainsSensitiveWord(content)
      // return result

      // 临时实现：检查一些基本的敏感词
      const sensitiveWords = ['敏感词1', '敏感词2'] // 实际项目中应该从服务器获取
      return sensitiveWords.some((word) => content.includes(word))
    } catch (error) {
      console.error('敏感词检查失败:', error)
      return false
    }
  }

  // 获取渲染性能统计
  const getRenderingStats = () => {
    return {
      ...renderingStats.value,
      cacheSize: contentCache.size,
      cacheEfficiency:
        renderingStats.value.cacheHits + renderingStats.value.cacheMisses > 0
          ? (
              (renderingStats.value.cacheHits /
                (renderingStats.value.cacheHits + renderingStats.value.cacheMisses)) *
              100
            ).toFixed(2) + '%'
          : '0%',
    }
  }

  // 清理缓存
  const clearCache = () => {
    contentCache.clear()
    renderingStats.value.cacheHits = 0
    renderingStats.value.cacheMisses = 0
  }

  // 重置性能统计
  const resetRenderingStats = () => {
    renderingStats.value = {
      totalRenderTime: 0,
      renderCount: 0,
      averageRenderTime: 0,
      lastRenderTime: 0,
      cacheHits: 0,
      cacheMisses: 0,
    }
  }

  // 切换思考过程显示（仅开发环境）
  const toggleThinkingProcess = () => {
    if (import.meta.env.DEV) {
      showThinkingProcess.value = !showThinkingProcess.value
      // 在开发环境中提供调试信息
      if (import.meta.env.DEV) {
        // eslint-disable-next-line no-console
        console.log(`思考过程显示: ${showThinkingProcess.value ? '开启' : '关闭'}`)
      }
    }
  }

  // 切换打字机效果
  const toggleTypewriter = () => {
    typewriterEnabled.value = !typewriterEnabled.value
  }

  // 设置打字机速度
  const setTypewriterSpeed = (speed: number) => {
    typewriterSpeed.value = Math.max(10, Math.min(200, speed)) // 限制在 10-200ms 之间
  }

  return {
    loading,
    models,
    loadingText,
    processing,
    saveMessage,
    sendToAI,
    stopProcessing,
    checkSensitiveWords,
    // 性能监控相关
    renderingStats: renderingStats.value,
    getRenderingStats,
    clearCache,
    resetRenderingStats,
    // 思考过程控制（仅开发环境）
    showThinkingProcess: showThinkingProcess.value,
    toggleThinkingProcess,
    // 打字机效果控制
    typewriterEnabled: typewriterEnabled.value,
    typewriterSpeed: typewriterSpeed.value,
    toggleTypewriter,
    setTypewriterSpeed,
    processStreamResponse,
  }
}
